package service

import (
	"errors"
	"fmt"
	"github.com/jinzhu/copier"
	"go-demo/common/global"
	"go-demo/mvc/model"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

type UserService struct {
	DB *gorm.DB
}

func NewUserService(db *gorm.DB) *UserService {
	return &UserService{DB: db}
}

func (us UserService) Register(registerForm *model.RegisterForm) (err error) {
	var user model.User

	// 查找用户是否已存在
	result := global.App.Mysql.First(&user, "user_account = ?", registerForm.UserAccount)
	if result.Error == nil {
		return fmt.Errorf("用户已存在")
	}

	// 创建新用户
	user.UserAccount = registerForm.UserAccount
	user.Password = registerForm.Password

	// 保存用户到数据库
	return global.App.Mysql.Create(&user).Error
}

func (us UserService) Login(loginForm *model.LoginForm) (string, error) {
	userAccount := loginForm.UserAccount
	password := loginForm.Password
	var user model.User

	// 查找用户
	if err := us.DB.Where("user_account = ?", userAccount).First(&user).Error; err != nil {
		return "", errors.New("user not found")
	}
	// 检查密码（假设使用 bcrypt 进行哈希比较）
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		return "", errors.New("password incorrect")
	}
	// 生成token
	token, err := GenerateJWT(user.ID)
	if err != nil {
		return "", errors.New("token generate failed")
	}

	return token, nil
}

func (us UserService) GetUserVoByID(id uint) (model.UserVo, error) {
	var user model.User
	user.ID = id
	result := us.DB.First(&user)

	var userVO model.UserVo
	if result.Error != nil {
		copier.Copy(&userVO, &user)
		return userVO, result.Error
	}
	return userVO, nil
}
